#第四次作业

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price


class Member:
    def __init__(self, level="普通"):
        self.level = level

    @property
    def discount_rate(self):
        """根据会员等级返回折扣率"""
        rates = {
            "普通": 1.0,
            "白银": 0.9,
            "黄金": 0.8,
            "钻石": 0.7
        }
        return rates.get(self.level, 1.0)


class CartItem:
    def __init__(self, product, qty, member=None):
        self.product = product
        self.qty = qty
        self.member = member or Member()  # 默认为普通会员

    def subtotal(self):
        """计算商品小计（含折扣）"""
        return self.product.price * self.qty * self.member.discount_rate


class ShoppingCart:
    def __init__(self):
        self.items = []

    def add(self, product, qty=1, member=None):
        """添加商品到购物车"""
        self.items.append(CartItem(product, qty, member))

    def total(self):
        """计算总价（含折扣）"""
        return sum(item.subtotal() for item in self.items)

    def original_total(self):
        """计算原总价（不含折扣）"""
        return sum(item.product.price * item.qty for item in self.items)

    def show(self):
        """显示购物清单和价格"""
        print("-" * 40)
        for item in self.items:
            original_price = item.product.price * item.qty
            discount = original_price - item.subtotal()

            print(f"{item.product.name} ×{item.qty}\t￥{original_price:.2f}", end="")
            if item.member.discount_rate < 1.0:
                print(f" (会员{item.member.level}折后: ￥{item.subtotal():.2f}, 节省￥{discount:.2f})")
            else:
                print()

        print("-" * 40)
        original = self.original_total()
        final = self.total()
        print(f"商品总价: ￥{original:.2f}")
        if final < original:
            print(f"会员折扣: -￥{original - final:.2f}")
        print(f"应付总额: ￥{final:.2f}")


# --- 测试 ---
# 创建商品
apple = Product("苹果", 3.5)
bread = Product("面包", 4.0)
milk = Product("牛奶", 5.5)

# 创建会员
silver_member = Member("白银")
gold_member = Member("黄金")
diamond_member = Member("钻石")

# 创建购物车
cart = ShoppingCart()

# 添加商品（不同会员等级）
cart.add(apple, 4)  # 普通会员
cart.add(bread, 2, silver_member)  # 白银会员
cart.add(milk, 3, gold_member)  # 黄金会员

# 显示购物清单
cart.show()